#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;
#define NUM 1024

// child
void Writer(int wfd)
{
    string s = "你好父进程，我是子进程";
    pid_t self = getpid();
    int number = 0, time = 5;

    char buffer[NUM];
    while (true)
    {
        sleep(1);
        // 构建发送字符串
        buffer[0] = 0;
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), self, number++);
        cout << buffer << endl;
        // 发送/写入给父进程, system call
        write(wfd, buffer, strlen(buffer)); // strlen(buffer) + 1???
    }
    cout << "子进程数据发送完成" << endl;
}

// father
void Reader(int rfd)
{
    char buffer[NUM];

    buffer[0] = 0;
    ssize_t n = read(rfd, buffer, sizeof(buffer) - 1); // 预留\0的位置
    if (n > 0)
    {
        buffer[n] = 0; // 手动添加\0
        cout << "父进程收到子进程的消息[" << getpid() << "]# " << buffer << endl;
    }
    else if (n == 0)
    {
        printf("father read file done!\n");
    }
    else
        cout << endl;
}

int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if (n == -1)
    {
        perror("pipe");
        return -1;
    }

    // 下面实现的是子进程写，父进程读
    pid_t id = fork();
    if (id < 0)
        return -2;

    // chlid
    if (id == 0)
    {
        close(pipefd[0]); // 关闭读，子进程只写
        // 子进程的通信过程
        cout << "子进程开始传输数据" << endl;
        Writer(pipefd[1]);
        sleep(1);
        cout << "子进程关闭写端" << endl;
        close(pipefd[1]); // 通信完毕后关闭写端
        exit(0);
    }

    // father
    close(pipefd[1]); // 关闭写，父进程只读
    // 父进程的通信过程
    cout << "父进程开始读取数据" << endl;
    Reader(pipefd[0]);

    close(pipefd[0]); // 通信完毕后关闭读端
    int status;
    waitpid(id,&status,0);
    cout<<"等待的子进程："<<id<<" 退出码："<<WEXITSTATUS(status)\
    <<" 收到的终止信号："<<WTERMSIG(status)<<endl; 
    return 0;
}